<template>
  <div class="page-container">
    <div class="page-header">
      <h2>工单管理</h2>
      <p>管理系统中的所有工单信息</p>
    </div>
    
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="工单标题">
          <el-input 
            v-model="searchForm.title" 
            placeholder="请输入工单标题" 
            clearable
          />
        </el-form-item>
        <el-form-item label="客户">
          <el-select 
            v-model="searchForm.customerId" 
            placeholder="请选择客户" 
            clearable
            filterable
          >
            <el-option 
              v-for="item in customerOptions" 
              :key="item.id" 
              :label="item.companyName" 
              :value="item.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工单类型">
          <el-select v-model="searchForm.orderType" placeholder="请选择工单类型" clearable style="width: 140px">
            <el-option label="售前咨询" value="售前咨询" />
            <el-option label="技术支持" value="技术支持" />
            <el-option label="售后服务" value="售后服务" />
            <el-option label="投诉处理" value="投诉处理" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="待处理" value="待处理" />
            <el-option label="处理中" value="处理中" />
            <el-option label="待回单" value="待回单" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已关闭" value="已关闭" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 工具栏 -->
    <div class="table-toolbar">
      <div class="toolbar-left">
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          新建工单
        </el-button>
      </div>
      <div class="toolbar-right">
        <el-radio-group v-model="viewMode" size="small">
          <el-radio-button label="all">所有工单</el-radio-button>
          <el-radio-button label="my">我的工单</el-radio-button>
        </el-radio-group>
      </div>
    </div>
    
    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="tableData" stripe border>
      <el-table-column prop="orderCode" label="工单编号" width="120" />
      <el-table-column prop="title" label="工单标题" min-width="150" show-overflow-tooltip />
      <el-table-column prop="customerName" label="客户名称" width="150" show-overflow-tooltip />
      <el-table-column prop="orderType" label="工单类型" width="100" />
      <el-table-column prop="priority" label="优先级" width="80">
        <template #default="{ row }">
          <span :class="`priority-tag ${getPriorityClass(row.priority)}`">{{ row.priority }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.status)">{{ row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="assignedToName" label="处理人" width="100" />
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleView(row)">
            <el-icon><View /></el-icon>
            查看
          </el-button>
          <el-button type="primary" link @click="handleEdit(row)">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        :disabled="dialogMode === 'view'"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工单编号" prop="orderCode">
              <el-input v-model="formData.orderCode" placeholder="请输入工单编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单标题" prop="title">
              <el-input v-model="formData.title" placeholder="请输入工单标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户" prop="customerId">
              <el-select 
                v-model="formData.customerId" 
                placeholder="请选择客户" 
                filterable
              >
                <el-option 
                  v-for="item in customerOptions" 
                  :key="item.id" 
                  :label="item.companyName" 
                  :value="item.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联业务" prop="businessId">
              <el-select 
                v-model="formData.businessId"
                placeholder="请选择关联业务"
                filterable
                clearable
                :disabled="!formData.customerId"
              >
                <el-option 
                  v-for="item in businessOptions" 
                  :key="item.id" 
                  :label="item.businessName" 
                  :value="item.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单类型" prop="orderType">
              <el-select v-model="formData.orderType" placeholder="请选择工单类型">
                <el-option label="售前咨询" value="售前咨询" />
                <el-option label="技术支持" value="技术支持" />
                <el-option label="售后服务" value="售后服务" />
                <el-option label="投诉处理" value="投诉处理" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="formData.priority" placeholder="请选择优先级">
                <el-option label="低" value="低" />
                <el-option label="中" value="中" />
                <el-option label="高" value="高" />
                <el-option label="紧急" value="紧急" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态" :disabled="dialogMode === 'create'">
                <el-option label="待处理" value="待处理" />
                <el-option label="处理中" value="处理中" />
                <el-option label="待回单" value="待回单" />
                <el-option label="已完成" value="已完成" />
                <el-option label="已关闭" value="已关闭" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分配给" prop="assignedTo">
              <el-select 
                v-model="formData.assignedTo" 
                placeholder="请选择处理人" 
                filterable
                clearable
              >
                <el-option 
                  v-for="item in employeeOptions" 
                  :key="item.id" 
                  :label="item.realName" 
                  :value="item.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="问题描述" prop="description">
              <el-input 
                v-model="formData.description" 
                type="textarea" 
                :rows="4"
                placeholder="请输入问题描述" 
              />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="dialogMode !== 'create'">
            <el-form-item label="解决方案" prop="solution">
              <el-input 
                v-model="formData.solution" 
                type="textarea" 
                :rows="4"
                placeholder="请输入解决方案" 
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div v-if="dialogMode === 'view'">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </div>
        <div v-else>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { 
  getWorkOrders, 
  getMyWorkOrders,
  getWorkOrder,
  createWorkOrder, 
  updateWorkOrder, 
  deleteWorkOrder,
  assignWorkOrder,
  updateWorkOrderStatus,
  addWorkOrderSolution
} from '@/api/workOrders'
import { getCustomers } from '@/api/customers'
import { getBusinesses } from '@/api/businesses'
import { getEmployees } from '@/api/employees'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const submitLoading = ref(false)
const customerOptions = ref([])
const businessOptions = ref([])
const employeeOptions = ref([])
const viewMode = ref('all') // all, my

// 搜索表单
const searchForm = reactive({
  title: '',
  customerId: '',
  orderType: '',
  status: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 弹窗相关
const dialogVisible = ref(false)
const dialogMode = ref('create') // create, edit, view
const formRef = ref()

// 表单数据
const formData = reactive({
  id: null,
  orderCode: '',
  title: '',
  customerId: '',
  businessId: '',
  orderType: '技术支持',
  priority: '中',
  status: '待处理',
  assignedTo: '',
  description: '',
  solution: ''
})

// 表单验证规则
const formRules = {
  orderCode: [
    { required: true, message: '请输入工单编号', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请输入工单标题', trigger: 'blur' }
  ],
  customerId: [
    { required: true, message: '请选择客户', trigger: 'change' }
  ],
  orderType: [
    { required: true, message: '请选择工单类型', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入问题描述', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  const titles = {
    create: '新建工单',
    edit: '编辑工单',
    view: '查看工单'
  }
  return titles[dialogMode.value]
})

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const statusMap = {
    '待处理': 'info',
    '处理中': 'primary',
    '待回单': 'warning',
    '已完成': 'success',
    '已关闭': 'info'
  }
  return statusMap[status] || 'info'
}

// 获取优先级样式类
const getPriorityClass = (priority) => {
  const priorityMap = {
    '低': 'low',
    '中': 'medium', 
    '高': 'high',
    '紧急': 'urgent'
  }
  return priorityMap[priority] || 'medium'
}

// 获取表格数据
const getTableData = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    
    let response
    if (viewMode.value === 'my') {
      response = await getMyWorkOrders(params)
    } else {
      response = await getWorkOrders(params)
    }
    
    if (response.code === 200) {
      // 修复：后端返回的数据结构是 { data: [...], total: 10, page: 1, size: 10 }
      let responseData = response.data
      if (responseData && responseData.data && Array.isArray(responseData.data)) {
        tableData.value = responseData.data
        pagination.total = responseData.total || 0
        console.log('成功加载工单数据:', responseData.data.length, '条')
      } else if (responseData && Array.isArray(responseData)) {
        tableData.value = responseData
        pagination.total = responseData.length
      } else {
        console.warn('API返回的数据格式不正确:', responseData)
        tableData.value = []
        pagination.total = 0
      }
    }
  } catch (error) {
    console.error('获取工单列表失败:', error)
    ElMessage.error('获取工单列表失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 获取客户选项
const getCustomerOptions = async () => {
  try {
    const response = await getCustomers({ pageSize: 1000 })
    if (response.code === 200) {
      // 修复：后端返回的数据结构是 { data: [...], total: 10, page: 1, size: 10 }
      let responseData = response.data
      if (responseData && responseData.data && Array.isArray(responseData.data)) {
        customerOptions.value = responseData.data
      } else if (responseData && Array.isArray(responseData)) {
        customerOptions.value = responseData
      } else {
        customerOptions.value = []
      }
    }
  } catch (error) {
    console.error('获取客户选项失败:', error)
    ElMessage.error('获取客户选项失败')
  }
}

// 获取业务选项
const getBusinessOptions = async (customerId) => {
  try {
    if (!customerId) {
      businessOptions.value = []
      return
    }
    
    const response = await getBusinesses({ customerId, pageSize: 1000 })
    if (response.code === 200) {
      // 修复：后端返回的数据结构是 { data: [...], total: 10, page: 1, size: 10 }
      let responseData = response.data
      if (responseData && responseData.data && Array.isArray(responseData.data)) {
        businessOptions.value = responseData.data
      } else if (responseData && Array.isArray(responseData)) {
        businessOptions.value = responseData
      } else {
        businessOptions.value = []
      }
    }
  } catch (error) {
    console.error('获取业务选项失败:', error)
    ElMessage.error('获取业务选项失败')
  }
}

// 获取员工选项
const getEmployeeOptions = async () => {
  try {
    const response = await getEmployees({ pageSize: 1000 })
    if (response.code === 200) {
      // 修复：后端返回的数据结构是 { data: [...], total: 10, page: 1, size: 10 }
      let responseData = response.data
      if (responseData && responseData.data && Array.isArray(responseData.data)) {
        employeeOptions.value = responseData.data
      } else if (responseData && Array.isArray(responseData)) {
        employeeOptions.value = responseData
      } else {
        employeeOptions.value = []
      }
    }
  } catch (error) {
    console.error('获取员工选项失败:', error)
    ElMessage.error('获取员工选项失败')
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getTableData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    title: '',
    customerId: '',
    orderType: '',
    status: ''
  })
  handleSearch()
}

// 新建工单
const handleCreate = () => {
  dialogMode.value = 'create'
  resetFormData()
  
  // 检查URL参数是否有预设值
  const query = route.query
  if (query.create && query.businessId && query.customerId) {
    formData.businessId = parseInt(query.businessId)
    formData.customerId = parseInt(query.customerId)
    getBusinessOptions(formData.customerId)
  }
  
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row) => {
  dialogMode.value = 'edit'
  resetFormData()
  try {
    const response = await getWorkOrder(row.id)
    if (response.code === 200) {
      Object.assign(formData, response.data)
      
      // 获取该客户的业务列表
      await getBusinessOptions(formData.customerId)
    }
    dialogVisible.value = true
  } catch (error) {
    console.error('获取工单详情失败:', error)
    ElMessage.error('获取工单详情失败')
  }
}

// 查看
const handleView = (row) => {
  router.push(`/dashboard/work-orders/detail/${row.id}`)
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除工单"${row.title}"吗？`, '确认删除', {
      type: 'warning'
    })
    
    await deleteWorkOrder(row.id)
    ElMessage.success('删除成功')
    getTableData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.page = 1
  getTableData()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.page = val
  getTableData()
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    submitLoading.value = true
    
    if (dialogMode.value === 'create') {
      await createWorkOrder(formData)
      ElMessage.success('新建工单成功')
    } else {
      const oldStatus = tableData.value.find(item => item.id === formData.id)?.status
      
      // 如果状态有变更，先更新状态
      if (oldStatus && formData.status !== oldStatus) {
        await updateWorkOrderStatus(formData.id, formData.status)
      }
      
      // 如果有分配人，处理分配
      if (formData.assignedTo) {
        await assignWorkOrder(formData.id, formData.assignedTo)
      }
      
      // 如果有解决方案，添加解决方案
      if (formData.solution) {
        await addWorkOrderSolution(formData.id, formData.solution)
      }
      
      // 更新其他信息
      await updateWorkOrder(formData.id, formData)
      
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    getTableData()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 弹窗关闭
const handleDialogClose = () => {
  formRef.value?.resetFields()
  resetFormData()
  dialogVisible.value = false
  
  // 如果是从其他页面跳转过来的创建操作，返回到原页面
  if (route.query.create && route.query.businessId) {
    router.replace('/dashboard/work-orders')
  }
}

// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    id: null,
    orderCode: '',
    title: '',
    customerId: '',
    businessId: '',
    orderType: '技术支持',
    priority: '中',
    status: '待处理',
    assignedTo: '',
    description: '',
    solution: ''
  })
}

// 监听客户变更，获取对应的业务列表
watch(() => formData.customerId, async (newVal) => {
  formData.businessId = ''
  if (newVal) {
    await getBusinessOptions(newVal)
  }
})

// 监听视图模式变化
watch(viewMode, () => {
  handleSearch()
})

// 页面初始化
onMounted(() => {
  getTableData()
  getCustomerOptions()
  getEmployeeOptions()
  
  // 如果是从其他页面跳转过来的创建操作
  if (route.query.create) {
    handleCreate()
  }
})
</script>

<style lang="scss" scoped>
.page-header {
  margin-bottom: 20px;
  
  h2 {
    font-size: 24px;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
  }
  
  p {
    color: #666;
    font-size: 14px;
  }
}
</style> 